package oss

import (
	"time"

	"github.com/lab-online/pkg/logger"
	"github.com/lab-online/pkg/util"
	"github.com/minio/minio-go/v7"
	"github.com/minio/minio-go/v7/pkg/credentials"
)

type Options struct {
	Endpoint        string
	UseSSL          bool
	AccessKeyID     string
	SecretAccessKey string
}

type OSSManagerBuilder interface {
	New() (OSSManager, error)
}

type OSSManager interface {
	NewBucket(name string, region string, locking bool) (BucketManager, error)
	RemoveBucket(name string) error
	PresignedPutObjectURL(bucketName string, objectKey string, expire time.Duration) (string, error)
}

func (opt *Options) New() (OSSManager, error) {
	minioClient, err := util.BackoffRetry(opt.connectMinio, &util.ExponentialOption{
		InitialDelay: time.Second * 2,
		Exponential:  2,
		Retry:        5,
	})

	if err != nil {
		return nil, err
	}

	return &MinioClient{
		minio: minioClient,
	}, nil
}

func (opt *Options) connectMinio() (*minio.Client, error) {
	logger.Info("Connecting to Minio", opt)
	return minio.New(opt.Endpoint, &minio.Options{
		Creds: credentials.NewStaticV4(opt.AccessKeyID, opt.SecretAccessKey, ""),
	})
}
